package com.x.netty.netty.file;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;

/**
 * @Author _G5niusX
 * @Date 2018/5/27 11:00
 */
public final class FileNettyClient {
    private final String ip;
    private final int port;

    public FileNettyClient(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }

    public void send(final ByteBuf byteBuf) throws InterruptedException {
        EventLoopGroup eventExecutors = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventExecutors).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast(new FileClientHandler(byteBuf));
            }
        });
        ChannelFuture channelFuture = bootstrap.connect(ip, port).sync();
        channelFuture.channel().closeFuture().sync();
    }

    public static void main(String[] args) throws InterruptedException {
        FileNettyClient fileNettyClient = new FileNettyClient("127.0.0.1", 9000);
        fileNettyClient.send(Unpooled.copiedBuffer("test", CharsetUtil.UTF_8));
    }
}
